package com.gao.d_selector.d;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @author gao
 * @time 2020/08/11 18:49:56
 */
public class TimeServer {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;

    public TimeServer() throws IOException {
        // 创建选择器
        selector = Selector.open();
        // 建立服务器
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8888));
        serverSocketChannel.configureBlocking(false);
        System.out.println("服务器已经建立...");
    }


    public void start()  {
        try {
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            while (true) {
                int n = selector.select();
                if (n > 0) {
                    Set<SelectionKey> selectedKeys = selector.selectedKeys();
                    Iterator<SelectionKey> it = selectedKeys.iterator();
                    while (it.hasNext()) {
                        SelectionKey key = it.next();
                         it.remove();
                        // 以下每一个判断前都加上key.isValid()，是为了防止当客户端退出后
                        // 服务器端仍然使用无效的key，比如，在服务器端的read方法中，服务器
                        // 读取到了"exit"，于是和客户端断开连接了，而从read方法返回出来后
                        // 如果下面的判断没有加上key.isValid()，则直接抛出异常，导致服务器
                        // 中断...
                        if (key.isValid() && key.isAcceptable()) {
                            accept(key);
                        }
                        if (key.isValid() && key.isReadable()) {
                            read(key);
                        }
                        if (key.isValid() && key.isWritable()) {
                            write(key);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void write(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            Date now = new Date();
            ByteBuffer buffer = ByteBuffer.wrap(now.toString().getBytes());
            channel.write(buffer);
            System.out.println("send server time to client...");
            key.interestOps(SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void read(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(100);
            // write to buffer
            channel.read(buffer);
            // write mode to read mode
            buffer.flip();
            byte[] readBytes = new byte[buffer.limit()];
            // read from buffer, to readBytes
            buffer.get(readBytes);
            String msg = new String(readBytes);
            System.out.println("recv from client：" + msg);
            if ("what's the time?".equalsIgnoreCase(msg)) {
                key.interestOps(SelectionKey.OP_WRITE);
            }
            if ("exit".equalsIgnoreCase(msg)) {
                key.cancel();
                channel.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void accept(SelectionKey key) {
        try {
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
            SocketChannel channel = serverSocketChannel.accept();
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
            System.out.println("新客户端加入");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) throws IOException {
        TimeServer timeServer = new TimeServer();
        timeServer.start();
    }

}
